package com.liaozibo.jekyll.service;

import com.liaozibo.jekyll.dao.CosOperation;
import com.liaozibo.jekyll.property.JekyllProperties;
import com.liaozibo.jekyll.property.TencentCosProperties;
import com.liaozibo.jekyll.util.ConsoleUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.file.Path;
import java.util.List;
import java.util.Objects;
import java.util.Scanner;

@Service
@Slf4j
public class CosService {

    @Autowired
    private JekyllProperties jekyllProperties;

    @Autowired
    private TencentCosProperties tencentCosProperties;

    @Autowired
    private CosOperation cosOperation;

    public void listBuckets() {
        List<String> bucketNameList = cosOperation.listBucketNames();
        for (String bucketName : bucketNameList) {
            ConsoleUtils.stdout(bucketName);
        }
    }

    /**
     * 创建存储桶并启用静态网站功能
     * */
    public void initBucket() {
        String bucketName = tencentCosProperties.getBucketName();
        log.info("创建存储桶：" + bucketName);
        cosOperation.createBucket(bucketName);
        log.info("启用静态网站功能");
        cosOperation.enableStaticSite(bucketName);
    }

    public void deleteBucket() {
        String bucketName = tencentCosProperties.getBucketName();
        ConsoleUtils.stdout("即将删除存储桶：" + bucketName);
        ConsoleUtils.stdout("请输出存储桶名称确认输出：");
        String inputName = null;
        try (Scanner scanner = new Scanner(System.in)) {
            inputName = scanner.nextLine();
        }
        if (Objects.equals(inputName, bucketName)) {
            doDeleteBucket(bucketName);
            ConsoleUtils.stdout("删除成功！");
        } else {
            ConsoleUtils.stdout("输出名称不匹配");
        }
    }

    private void doDeleteBucket(String bucketName) {
        cosOperation.deleteBucket(bucketName);
    }

    public void deploy() throws InterruptedException {
        String bucketName = tencentCosProperties.getBucketName();
        Path sitePath = jekyllProperties.getSitePath();
        log.info("开始清空存储桶：" + bucketName);
        cosOperation.truncate(bucketName);
        log.info("清空存储桶完成！：" + bucketName);

        log.info("开始上传网站文件：" + sitePath + " -> " + bucketName);
        cosOperation.uploadDirectory(sitePath, bucketName);
        log.info("上传完成！");
        log.info("访问网站：" + tencentCosProperties.getStaticSiteUrl());
    }

}
